<?php

namespace app\payqr\controller;

use AlibabaCloud\Client\AlibabaCloud;
use app\AdminRest;
use app\agent\model\Cardauth2DefaultModel;
use app\card\model\CardCount;
use app\dynamic\info\PermissionDynamic;
use app\payqr\model\CardauthConfig;
use app\payqr\model\CardConfig;
use app\payqr\model\CardFormId;
use app\payqr\model\CardGroupSending;
use app\payqr\model\CardJob;
use app\payqr\model\CardArticles;
use app\payqr\model\CardCompany;
use app\payqr\model\CardForm;
use app\payqr\model\CardModular;
use app\payqr\model\CardShopOrder;
use app\payqr\model\CardTimeline;
use app\payqr\model\CardTimelineComment;
use app\payqr\model\CardUser;
use app\payqr\model\PayqrCarousel;
use app\payqr\model\PayQrConfig;
use app\payqr\model\PayQrRecord;
use app\payqr\model\TimelineTimeline;
use app\payqr\model\UserInfo;
use app\payqr\model\UserPhone;
use app\payqr\model\UserSend;
use app\shop\model\AdminShopOrderGoods;
use app\shop\model\IndexShopOrder;
use app\validate\AdminCardCompany;
use app\validate\AdminCardModular;
use app\payqr\validate\AdminQrCheck;
use app\payqr\validate\AdminTimeline;
use think\App;
use think\facade\Db;

class AdminOfficer extends AdminRest
{

    protected $page;
    protected $list_rows;

    // 继承 验证用户登陆
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->page = !empty($this->_param['page']) ? $this->_param['page'] : 1;
        $this->list_rows = !empty($this->_param['limit']) ? $this->_param['limit'] : 10;
    }

    /**
     * @Purpose: 官网
     *
     * @Method: GET
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function index()
    {
        $modular = new CardModular();
        $keyword = isset($this->_param['keyword']) ? $this->_param['keyword'] : '';
        $where[] = ['uniacid' , '=', $this->_uniacid];
        if ($keyword) {
            $where[] = ['name', 'like', "%{$keyword}%"];
        }
        $list = $modular->lists($this->page, $this->list_rows, $where);
        return $this->success($list);
    }

    public function save()
    {
        $data = $this->_input;
        $modular = new AdminCardModular();
        $result = $modular->check($data);
        if (!$result) {
            return $this->error($modular->getError());
        }
        $modular = new CardModular();
        if (!empty($data['cover'])) {
            $data['cover'] = trim(implode(',', $data['cover']), ',');
        }
        $data['uniacid'] = $this->_uniacid;
        $data['table_name'] = $modular->type_table($data['type']);
        $modular->createRow($data);
        return $this->success([]);
    }

    public function update()
    {
        $data = $this->_input;
        $adminModular = new AdminCardModular();
        $result = $adminModular->check($data);
        if (!$result) {
            return $this->error($adminModular->getError());
        }
        $modular = new CardModular();
        $id = $modular->getID($data['id']);
        if (!$id) {
            return $this->error('数据不存在');
        }
        $where = [
            'id' => $data['id'],
        ];
        if (!empty($data['cover'])) {
            $data['cover'] = trim(implode(',', $data['cover']), ',');
        }
        $modular->upsave($where, $data);
        return $this->success([]);
    }

    public function delete()
    {
        $verify = ['id' => 'required'];
        $data = lbGetParamVerify($this->_input, $verify);
        $modular = new CardModular();
        $id = $modular->getID($data['id']);
        if (!$id) {
            return $this->error('数据不存在');
        }
        $where = [
            'id' => $data['id'],
        ];
        $modular->destroyRow($where);
        return $this->success([]);
    }

    public function changeLower()
    {
        $verify = ['id' => 'required'];
        $data = lbGetParamVerify($this->_input, $verify);
        $modular = new CardModular();
        $modular->change_status($data);
        return $this->success([]);
    }

    public function msgProcess()
    {
        $verify = ['id' => 'required', 'modular_id' => 'required'];
        $data = lbGetParamVerify($this->_input, $verify);
        $modular = new CardModular();
        $info = $modular->infoDetail($data);
        $form = new CardForm();
        $form->upsave(['id' => $info['id']], ['status' => 2]);
        return $this->success([]);
    }

    public function msgProcessDel()
    {
        $verify = ['id' => 'required', 'modular_id' => 'required'];
        $data = lbGetParamVerify($this->_input, $verify);
        $modular = new CardModular();
        $info = $modular->infoDetail($data);
        $form = new CardForm();
        $form->destroyRow(['id' => $info['id']]);
        return $this->success([]);
    }

    public function updateJobs()
    {
        $verify = ['id' => 'required', 'modular_id' => 'required', 'method' => 0];
        $params = lbGetParamVerify($this->_input, $verify);
        $status = $params['method'];
        if ($status == 2) {
            $status = -1;
        }
        $modular = new CardModular();
        $modular->updateDetail($params, ['status' => $status]);
        return $this->success([]);
    }

    public function updateContents()
    {
        $verify = ['id' => 'required', 'modular_id' => 'required'];
        $params = lbGetParamVerify($this->_input, $verify);
        $modular = new CardModular();
        $modular->updateDetail($params, $this->_input);
        return $this->success([]);
    }

    public function createContents()
    {
        $verify = ['modular_id' => 'required'];
        lbGetParamVerify($this->_input, $verify);
        $modular = new CardModular();
        $this->_input['uniacid'] = $this->_uniacid;
        $modular->createDetail($this->_input);
        return $this->success([]);
    }

    public function modular_content_info()
    {
        $verify = ['id' => 'required', 'modular_id' => 'required'];
        $params = lbGetParamVerify($this->_param, $verify);
        $modular = new CardModular();
        $list = $modular->infoDetail($params, 1);
        return $this->success($list);
    }

    public function modular_info()
    {
        $verify = ['id' => 'required'];
        $params = lbGetParamVerify($this->_param, $verify);
        $modular = new CardModular();
        $list = $modular->getTable($params['id']);
        return $this->success($list);
    }

    public function read()
    {
        $verify = ['id' => 'required'];
        $data = lbGetParamVerify($this->_param, $verify);
        $modular = new CardModular();
        $id = $modular->getID($data['id']);
        if (!$id) {
            return $this->error('数据不存在');
        }
        $keyword = isset($this->_param['keyword']) ? $this->_param['keyword'] : '';
        $where[] = [
            ['status', '<>', -1],
            ['uniacid', '=', $this->_uniacid]
        ];
        $list = $modular->listinfo($data['id'], $this->page, $this->list_rows, $where, 1, $keyword);
        return $this->success($list);
    }

    /**
     * @Purpose: 动态列表
     *
     * @Method: GET
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function timelines()
    {
        $keyword = isset($this->_param['keyword']) ? $this->_param['keyword'] : '';
        $where = [['a.uniacid', '=', $this->_uniacid], ['a.status', '>', -1]];
        if ($keyword) {
            $where[] = ['a.title', 'like', "%{$keyword}%"];
        }
        $line = new CardTimeline();
        $data = $line->dtlist($this->page, $this->list_rows, $where);
        return $this->success($data);
    }

    /**
     * @Purpose: 动态详情
     *
     * @Method: GET
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function timelines_info()
    {
        $verify = ['id' => 'required'];
        $params = lbGetParamVerify($this->_param, $verify);
        $line = new CardTimeline();
        $where['id'] = $params['id'];
        $where['uniacid'] = $this->_uniacid;
        $data = $line->admin_get_info($where);
        return $this->success($data);
    }

    /**
     * @Purpose: 动态修改
     *
     * @Method: POST
     *
     * @Param：$timeline_id   number  动态id
     * @Param：$method   number  操作类型  0 = 下架 1 = 上架 2 = 删除
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function updateTimelines()
    {

        $verify = ['timeline_id' => 'required', 'method' => 0];
        $params = lbGetParamVerify($this->_input, $verify);
        $status = $params['method'];
        if ($status == 2) {
            $status = -1;
        }
        $line = new CardTimeline();
        $data = [
            'status' => $status
        ];
        $result = $line->upsave(['id' => $params['timeline_id']], $data);
        if ($result === false) {
            return $this->error('operation failed');
        }
        return $this->success([]);
    }

    public function createLines()
    {
        $data = $this->_input;
        $timeline = new AdminTimeline();
        $result = $timeline->check($data);
        if (!$result) {
            return $this->error($timeline->getError());
        }

        if (!empty($data['cover'])) {
            if(count($data['cover'])>9){
                return $this->error('图片最多上传九张');
            }
            $data['cover'] = trim(implode(',', $data['cover']), ',');
        }
        $line = new CardTimeline();
        $data['uniacid'] = $this->_uniacid;
        $count = $line->getCount(['uniacid'=>$this->_uniacid]);

        $permissionDynamic = new PermissionDynamic($this->_uniacid);
        $authNumber = $permissionDynamic->getAuthNumber();
        if($authNumber != 0 && $count>=$authNumber){
            return $this->error('发布动态已上限');
        }

        $data['user_id'] = 0;//$this->_user['user_id'];
        if ($data['content']) {
            $data['content'] = htmlspecialchars($data['content']);
        }
        $res = $line->createRow($data);
        if ($res === false) {
            return $this->error('operation failed');
        }
        return $this->success([]);
    }

    public function updateLines()
    {
        $data = $this->_input;
        $timeline = new AdminTimeline();
        $result = $timeline->check($data);
        if (!$result) {
            return $this->error($timeline->getError());
        }
        $line = new CardTimeline();
        $id = $line->getID($data['id']);
        if (!$id) {
            return $this->error('数据不存在');
        }
        if (!empty($data['cover'])) {
            if(count($data['cover'])>9){
                return $this->error('图片最多上传九张');
            }
            $data['cover'] = trim(implode(',', $data['cover']), ',');
        }
        if ($data['content']) {
            $data['content'] = htmlspecialchars($data['content']);
        }
        $res = $line->upsave(['id' => $data['id']], $data);
        if ($res === false) {
            return $this->error('operation failed');
        }
        return $this->success([]);
    }

    public function comment_list()
    {
        $comment = new CardTimelineComment();
        $where['a.uniacid'] = $this->_uniacid;
        $list = $comment->getlist($where, $this->page, $this->list_rows);
        return $this->success($list);
    }

    public function comment_del()
    {
        $verify = ['id' => 'required'];
        $params = lbGetParamVerify($this->_input, $verify);
        $comment = new CardTimelineComment();
        $comment->upsave(['id' => $params['id']], ['status' => -1]);
        return $this->success([]);
    }

    public function company_list()
    {
        $card_company = new CardCompany();
        $where = [
            ['status', '<>', -1],
            ['pid', '=', 0],
            ['uniacid', '=', $this->_uniacid]
        ];
        $topCompany = $card_company->getlist($where);
        $whereson = [
            ['status', '<>', -1],
            ['pid', '<>', 0],
            ['uniacid', '=', $this->_uniacid]
        ];
        $sonCompany = $card_company->getlist($whereson);
        $list = $card_company->handleCompanyLevel($topCompany, $sonCompany, 'children');
        return $this->success($list);
    }

    /**
     * @Purpose: 下架 / 上架 / 删除公司
     *
     * @Method: POST
     *
     * @Param：$company_id   number  公司id
     * @Param：$method   number  操作类型  0 = 下架 1 = 上架 2 = 删除
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function company_change()
    {
        $verify = ['id' => 'required', 'method' => 0];

        $params = lbGetParamVerify($this->_input, $verify);
        $company = new CardCompany();
        if ($params['method'] == 2 || $params['method'] == 0) {
            $list = $company->getCompanyUser($params['id']);
            $user = new UserInfo();
            $company_id = $user->getCompanyUser($params['id']);
            $list = array_merge($list, $company_id);
            $arr = $company->getCompanyName($list);
            if (count(array_filter($arr)) > 0) {
                $com_list = implode(',', $arr);
                return $this->error("[$com_list]公司下面还有员工存在无法删除或者下级该公司");
            }
        }
        $result = $company->updateStatus($params['id'], $params['method']);
        if ($result === false) {
            return $this->error('operation failed');
        }
        return $this->success([]);
    }
    function curl_get($type, $url, $cookie) {//type与url为必传、若无cookie则传空字符串

        if (empty($url)) {
            return false;
        }

        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        if($type){  //判断请求协议http或https
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        }
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        if(!empty($cookie))curl_setopt($ch,CURLOPT_COOKIE,$cookie);  //设置cookie
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }
    public function create_company()
    {
        $data = $this->_input;
        $validate = new AdminCardCompany();
        $result = $validate->check($data);
        if (!$result) {
            return $this->error($validate->getError());
        }
        $company = new CardCompany();
        $where = [
            ['name','=',$data['name']],['status','<>',-1],['pid','=',0],['uniacid','=',$this->_uniacid]
        ];
        $info = $company->getinfo($where);
        if($info&&$info['id'] != $data['id']){
            return $this->error('公司名称已存在');
        }
        if (!empty($data['culture'])) {
            $data['culture'] = trim(implode(',', $data['culture']), ',');
        }
        $data['uniacid'] = $this->_uniacid;

        if ($data['id']) {
            $company_id = $data['id'];
            unset($data['id']);
            $res = $company->upsave(['id' => $company_id], $data);
            unset($data['name']);
            $company->updateSonCompanyInfo($company_id, $data);
            longbingGetUserCompany($company_id ,$this->_uniacid ,true);
        } else {
            $res = $company->createRow($data);
        }
        if ($res === false) {
            return $this->error('operation failed');
        }

        return $this->success([]);
    }

    public function company_info()
    {
        $verify = ['id' => 'require'];
        $params = lbGetParamVerify($this->_param, $verify);
        $where = [
            ['uniacid', '=', $this->_uniacid], ['status', '>', -1], ['id', '=', $params['id']]
        ];
        $company = new CardCompany();
        $info = $company->getinfo($where);
        return $this->success($info);
    }

    /**
     * @Purpose: 新增 / 编辑 部门信息
     *
     * @Method: POST
     * @Param：  number  公司id 编辑公司信息是需要传入
     * @Param：$name   string  部门名
     * @Param：$method   method  操作类型 1 = 新增部门 2 = 修改部门
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function edit_department()
    {
        $verify = ['id' => 'require', 'name' => 'require', 'method' => 1];
        $params = lbGetParamVerify($this->_input, $verify);
        $company_id = $params['id'];
        $card_company = new CardCompany();
        //  新增部门
        if ($params['method'] == 1) {
            $company = $card_company->getinfo(['id' => $company_id],1);
            if (!$company) {
                return $this->error('company not found');
            }
            unset($company['id']);
            unset($company['create_time']);
            unset($company['update_time']);
            $company['name'] = $params['name'];
            $company['pid'] = $company_id;
            $company['status'] = 1;
            $key = 'CARD_AUTH_COMPANY_';
            $value = getCache($key, $this->_uniacid);
            if (!$value && false) {
                $company['pid'] = 0;
            }
            if($company['top_id'] == 0){
                $company['top_id'] = $company['pid'];
            }
            $company['uniacid'] = $this->_uniacid;
            $result = $card_company->createRow($company);
        } //  修改部门
        else if ($params['method'] == 2) {
            $result = $card_company->upsave(['id' => $company_id], ['name' => $params['name']]);
        } else {
            return $this->error('method failed');
        }

        if ($result === false) {
            return $this->error('operation failed');
        }

        return $this->success(['operation success']);
    }

    /**
     * @Purpose: 职务列表
     *
     * @Method: GET
     * @Return: mixed 查询返回值
     */
    public function positions()
    {

        $keyword = isset($this->_param['keyword']) ? $this->_param['keyword'] : '';
        $where = [['uniacid', '=', $this->_uniacid], ['status', '>', -1]];
        if ($keyword) {
            $where[] = ['name', 'like', "%{$keyword}%"];
        }
        $job = new CardJob();
        $data = $job->getlist($where, $this->page, $this->list_rows);
        return $this->success($data);
    }

    public function change_position()
    {
        $verify = ['id' => 'required', 'method' => 0];
        $params = lbGetParamVerify($this->_input, $verify);
        if ($params['method'] == 2) {
            $status = -1;
        } else {
            $status = $params['method'];
        }
        $job = new CardJob();
        $job->upsave(['id' => $params['id']], ['status' => $status]);
        return $this->success([]);
    }

    public function create_position()
    {
        $verify = ['id' => 0, 'name' => 'required', 'top' => 0];
        $params = lbGetParamVerify($this->_input, $verify);
        $job = new CardJob();
        $where = [
            ['name','=',$params['name']],['status','<>',-1],['uniacid','=',$this->_uniacid]
        ];
        $info = $job->getNameinfo($where);
        if($info&&$info['id'] != $params['id']){
            return $this->error('职务名称已存在');
        }
        if ($params['id']) {
            $job->upsave(['id' => $params['id']], ['name' => $params['name'], 'top' => $params['top']]);
        } else {
            $job->createRow([
                'name' => $params['name'], 'top' => $params['top'], 'uniacid' => $this->_uniacid
            ]);
        }
        return $this->success([]);
    }

    public function pay_list()
    {
        $card_user = new CardUser();
        $keyword = isset($this->_param['keyword']) ? $this->_param['keyword'] : '';
        $nickName = isset($this->_param['nikeName']) ? $this->_param['nikeName'] : '';
        $where[] = [['a.is_staff', '=', 1],['b.is_staff', '=', 1],['a.uniacid', '=', $this->_uniacid]];
        if ($keyword) {
            $where[] = ['b.name', 'like', "%{$keyword}%"];
        }
        if ($nickName) {
            $where[] = ['a.nickName', 'like', "%{$nickName}%"];
        }
        $list = $card_user->pay_list($where, $this->page, $this->list_rows);
        return $this->success($list);
    }

    public function pay_record()
    {
        $keyword = isset($this->_param['keyword']) ? $this->_param['keyword'] : '';
        $start_time = isset($this->_param['start_time']) ? strtotime($this->_param['start_time']) : '';
        $end_time = isset($this->_param['end_time']) ? strtotime($this->_param['end_time']) : '';
        if ($keyword) {
            $where[] = ['c.name', 'like', "%{$keyword}%"];
        }
        if ($start_time && $end_time) {
            $where[] = ['a.update_time', 'between', "$start_time,$end_time"];
        }
        $where[] = [
            ['a.uniacid', '=', $this->_uniacid],
            ['pay_status', '=', 1],
            ['a.status', '=', 1],
        ];
        $pay = new PayQrRecord();
        $list['list'] = $pay->getlist($this->page, $this->list_rows, $where);
        $list['total_money'] = $pay->total_money($where);
        return $this->success($list);
    }

    public function carousel()
    {
        $carousel = new PayqrCarousel();
        $where[] = [
            ['uniacid', '=', $this->_uniacid],
            ['status', '<>', -1],
        ];
        $list = $carousel->getlist($where, $this->page, $this->list_rows);
        return $this->success($list);
    }

    public function create_carousel()
    {
        $data = $this->_input;
        $verify = ['img' => 'required', 'top' => 'required'];
        $params = lbGetParamVerify($data, $verify);
        $carousel = new PayqrCarousel();
        $params['uniacid'] = $this->_uniacid;
        $params['img'] = trim(implode(',', $params['img']), ',');
        if (!empty($data['id'])) {
            $carousel->upsave(['id' => $data['id']], $params);
        } else {
            $carousel->createRow($params);
        }
        return $this->success([]);
    }

    public function change_carousel()
    {
        $data = $this->_input;
        $verify = ['id' => 'required', 'method' => 0];
        $params = lbGetParamVerify($data, $verify);
        $carousel = new PayqrCarousel();
        if ($params['method'] == 2) {
            $params['method'] = -1;
        }
        $carousel->upsave(['id' => $params['id']], ['status' => $params['method']]);
        return $this->success([]);
    }
    public function carousel_info(){
        $data = $this->_param;
        $verify = ['id' => 'required', 'method' => 0];
        $params = lbGetParamVerify($data, $verify);
        $carousel = new PayqrCarousel();
        $info = $carousel->getinfo(['id'=>$params['id']]);
        return $this->success($info);
    }
    public function qr_config()
    {
        $config = new PayQrConfig();
        $where['uniacid'] = $this->_uniacid;
        $info = $config->getinfo($where);
        return $this->success($info);
    }

    public function create_qr_config()
    {
        $data = $this->_input;
        $qr = new AdminQrCheck();
        $result = $qr->check($data);
        if (!$result) {
            return $this->error($qr->getError());
        }
        if ($data['first_full'] <= $data['first_reduce']) {
            return $this->error('满减金额设置错误');
        }
        $config = new PayQrConfig();
        if (!empty($data['company_logo'])) {
            $data['company_logo'] = trim(implode(',', $data['company_logo']), ',');
        }
        if ($data['id']) {
            $config->upsave(['uniacid' => $this->_uniacid], $data);
        } else {
            $config->createRow($data);
        }
        return $this->success([]);
    }

    public function create_pay()
    {
        $data = $this->_input;
        $verify = ['staff_id' => 'required'];
        $params = lbGetParamVerify($data, $verify);
        $user = new CardUser();
        $params['pid'] = $params['staff_id'];
        $src = getCache($data['staff_id'].'-'.'pay_qr');
        //$qr = $user->getPyCode($params['staff_id']);
        if(empty($src)||!is_file($src)){
            $miniPath = 'pay/pages/home';
            $src = longbingCreateWxCode($this->_uniacid,$params,$miniPath);
            if(isset($src['qr_path'])) $src = transImagesOne($src ,['qr_path'] ,$this->_uniacid);
            $src = $src['qr_path'];
            setCache($data['staff_id'].'-'.'pay_qr',$src);
            if ($src == '') {
                return $this->error('operation failed');
            }
            $user->upsave(['id' => $params['staff_id']], ['pay_qr' => $src]);
        }

        return $this->success(['src' => $src]);
    }

    public function download_pay()
    {
        $verify = ['id' => 'required'];
        $params = lbGetParamVerify($this->_param, $verify);
        $user = new CardUser();
        $user_info = $user->getPyCode($params['id']);
        if ($user_info['pay_qr']) {
            $file=  new \think\response\File($user_info['pay_qr']);
            return $file->name('my.jpg');
            //return download($user_info['pay_qr'], $user_info['pay_qr']);
        } else {
            return $this->error('获取失败');
        }
    }

    public function send_message()
    {
        $verify = ['type' => '0', 'content' => 'required'];
        $param = lbGetParamVerify($this->_input, $verify);
        $date = date('Y-m-d H:i');
        if ($param['type'] == 0) {
            $user = new CardUser();
            $user_list = $user->userAll(['a.uniacid' => $this->_uniacid]);
            $access_token = getAccessToken($this->_uniacid);
            if (!$access_token) {
                return $this->error('获取token失败');
            }
            $card_conf = new CardConfig();
            $config = $card_conf->getinfo(['uniacid' => $this->_uniacid]);
            $page = '';
            foreach ($user_list as $item) {
                $form = $item['formId'];
                if (!$form) {
                    continue;
                }
                $postData = [
                    'touser' => $item['openid'],
                    'template_id' => $config['mini_template_id'],
                    'page' => $page,
                    'form_id' => $form,
                    'data' => [
                        'keyword1' => ['value' => '系统通知'],
                        'keyword2' => ['value' => $param['content']],
                        'keyword3' => ['value' => $date],
                    ],
                ];
                $postData['page'] = 'longbing_card/pages/index/index';
                $postData = json_encode($postData);
                if (!$config['mini_template_id']) {
                    continue;
                }
                $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$access_token}";
                $tmp = [
                    'url' => $url,
                    'data' => $postData,
                ];
                $rest = lbCurlPost($tmp['url'], $tmp['data']);
                $rest = json_decode($rest, true);
                if ($rest['errcode'] == 0) {
                    $card_form = new CardFormId();
                    $card_form->destroyRow(['id' => $item['bid']]);
                }
            }

        } elseif ($param['type'] == 2) {
            $user = new UserInfo();
            $users = $user->userStaffAll(['a.uniacid' => $this->_uniacid, 'a.is_staff' => 1]);
            $access_token = getAccessToken($this->_uniacid);
            if (!$access_token) {
                return $this->error('获取token失败');
            }
            $card_conf = new CardConfig();
            $config = $card_conf->getinfo(['uniacid' => $this->_uniacid]);
            if ($config['notice_switch'] == 1) {
                if (!$config['wx_appid']) {
                    return false;
                }
                if (!$config['wx_tplid']) {
                    return false;
                }
                foreach ($users as $index => $item) {
                    $page = "longbing_card/staff/radar/radar";
                    $date = date('Y-m-d H:i');
                    $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token={$access_token}";
                    $data = [
                        'touser' => $item['openid'],
                        'mp_template_msg' => [
                            'appid' => $config['wx_appid'],
                            "url" => "http://weixin.qq.com/download",
                            'template_id' => $config['wx_tplid'],
                            'miniprogram' => [
                                'appid' => $config['appid'],
                                'pagepath' => $page,
                            ],
                            'data' => array(
                                'first' => array(
                                    'value' => '系统通知',
                                    'color' => '#c27ba0',
                                ),
                                'keyword1' => array(
                                    'value' => '管理员',
                                    'color' => '#93c47d',
                                ),
                                'keyword2' => array(
                                    'value' => $param['content'],
                                    'color' => '#0000ff',
                                ),
                                'remark' => array(
                                    'value' => $date,
                                    'color' => '#45818e',
                                ),
                            )
                        ],
                    ];
                    $data = json_encode($data);
                    $tmp = [
                        'url' => $url,
                        'data' => $data,
                    ];
                    $rest = lbCurlPost($tmp['url'], $tmp['data']);
                    $rest = json_decode($rest, true);
                    if ($rest['errcode'] == 0) {
                        $card_form = new CardFormId();
                        $card_form->destroyRow(['id' => $item['bid']]);
                        $send = new UserSend();
                        $send->createRow(['user_id' => $item['fans_id'], 'content' => $param['content'], 'uniacid' => $this->_uniacid, 'type' => 2]);
                    }
                }
            } elseif ($config['notice_switch'] == 2) {
                $access_token = qyGetAccessToken($this->_uniacid);
                if (!$access_token) {
                    return $this->error('获取token失败');
                }
                $appid = $config['corpid'];
                $appsecret = $config['corpsecret'];
                $agentid = $config['agentid'];

                if (!$appid || !$appsecret || !$agentid) {
                    return $this->error('配置信息不全');
                }
                foreach ($users as $index => $item) {
                    $touser = $item['ww_account'];
                    if (!$touser) {
                        continue;
                    }
                    $data = array(
                        'touser' => $touser,
                        'msgtype' => 'text',
                        'agentid' => $agentid,
                        'text' => array(
                            'content' => $param['content'],
                        ),
                    );
                    $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$access_token}";
                    $tmp = [
                        'url' => $url,
                        'data' => json_encode($data),
                    ];
                    $rest = lbCurlPost($tmp['url'], $tmp['data']);
                    $rest = json_decode($rest, true);
                    if ($rest['errcode'] == 0) {
                        $card_form = new CardFormId();
                        $card_form->destroyRow(['id' => $item['bid']]);
                        $send = new UserSend();
                        $send->createRow(['user_id' => $item['fans_id'], 'content' => $param['content'], 'uniacid' => $this->_uniacid, 'type' => 2]);
                    }
                }
            } else {
                $page = "longbing_card/staff/radar/radar";
                foreach ($users as $index => $item) {
                    $form = $item['formId'];
                    if (!$form) {
                        continue;
                    }
                    $postData = [
                        'touser' => $item['openid'],
                        'template_id' => $config['mini_template_id'],
                        'page' => $page,
                        'form_id' => $form,
                        'data' => [
                            'keyword1' => ['value' => '系统通知'],
                            'keyword2' => ['value' => $param['content']],
                            'keyword3' => ['value' => $date],
                        ],
                    ];

                    $postData['page'] = 'longbing_card/pages/index/index';
                    $postData = json_encode($postData);
                    if (!$config['mini_template_id']) {
                        continue;
                    }
                    $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$access_token}";
                    $tmp = [
                        'url' => $url,
                        'data' => $postData,
                    ];
                    $rest = lbCurlPost($tmp['url'], $tmp['data']);
                    $rest = json_decode($rest, true);
                    if ($rest['errcode'] == 0) {
                        $formid = new CardFormId();
                        $formid->destroyRow(['id' => $item['bid']]);
                        $send = new UserSend();
                        $send->createRow(['user_id' => $item['fans_id'], 'content' => $param['content'], 'uniacid' => $this->_uniacid, 'type' => 2]);
                    }
                }
            }
        } elseif ($param['type'] == 1) {
            $user = new CardUser();
            $users = $user->userAll(['a.uniacid' => $this->_uniacid, 'a.is_staff' => 0]);
            $access_token = getAccessToken($this->_uniacid);
            if (!$access_token) {
                return $this->error('获取token失败');
            }
            $card_conf = new CardConfig();
            $config = $card_conf->getinfo(['uniacid' => $this->_uniacid]);
            $page = '';
            $date = date('Y-m-d H:i');
            foreach ($users as $index => $item) {
                $form = $item['formId'];
                if (!$form) {
                    continue;
                }
                $postData = [
                    'touser' => $item['openid'],
                    'template_id' => $config['mini_template_id'],
                    'page' => $page,
                    'form_id' => $form,
                    'data' => [
                        'keyword1' => ['value' => '系统通知'],
                        'keyword2' => ['value' => $param['content']],
                        'keyword3' => ['value' => $date],
                    ],
                ];

                $postData['page'] = 'longbing_card/pages/index/index';
                $postData = json_encode($postData);
                if (!$config['mini_template_id']) {
                    continue;
                }
                $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$access_token}";
                $tmp = [
                    'url' => $url,
                    'data' => $postData,
                ];
                $rest = lbCurlPost($tmp['url'], $tmp['data']);
                $rest = json_decode($rest, true);
                if ($rest['errcode'] == 0) {
                    $formid = new CardFormId();
                    $formid->destroyRow(['id' => $item['bid']]);
                }
            }
        } else {
            return $this->error('类型错误');
        }
        return $this->success([]);
    }

    public function send_message_conf()
    {
        $verify = ['btn_sale' => 'required'];
        $params = lbGetParamVerify($this->_input, $verify);
        $config = new CardConfig();
        $config->upsave(['uniacid' => $this->_uniacid], $params);
        return $this->success([]);
    }

    public function send_conf_info()
    {
        $config = new CardConfig();
        $info = $config->getinfo(['uniacid' => $this->_uniacid]);
        return $this->success($info);
    }

    public function short_send()
    {
        $config = new CardConfig();
        $verify = ['default_voice_switch' => 'required', 'modular' => 'required', 'sign' => 'required'];
        $params = lbGetParamVerify($this->_input, $verify);
        //获取对应的手机号码
        $phone = new UserPhone();
        if ($params['default_voice_switch'] == 0) {
            $list = $phone->getAllPhone(['uniacid' => $this->_uniacid]);
        } elseif ($params['default_voice_switch'] == 1 || $params['default_voice_switch'] == 2) {
            $is_staff = $params['default_voice_switch'] == 1 ? 1 : 0;
            $user = new CardUser();
            $arr_userid = $user->getUserId(['uniacid' => $this->_uniacid, 'is_staff' => $is_staff]);
            $where = [
                ['uniacid', '=', $this->_uniacid],
                ['user_id', 'in', $arr_userid]
            ];
            $list = $phone->getAllPhone($where);
        } else {
            return $this->error('类型错误');
        }
        if ($list) {
            $config_info = $config->getinfo(['uniacid' => $this->_uniacid])->toArray();
            $phone = array_unique($list);
            $str_phone = implode(',', $phone);
            if (!$config_info['aliyun_sms_access_key_id'] || $config_info['aliyun_sms_access_key_secret']) {
                return $this->error('阿里云密钥账号不存在');
            }
            $info = $config->sendSms($str_phone, $config_info['aliyun_sms_access_key_id'], $config_info['aliyun_sms_access_key_secret'], $params['modular'], $params['sign']);
            return $this->success($info);
        } else {
            return $this->error('手机号不存在');
        }
    }

    public function edit_sms_conf()
    {
        $verify = ['aliyun_sms_access_key_id' => 'required', 'aliyun_sms_access_key_secret' => 'required'];
        $params = lbGetParamVerify($this->_input, $verify);
        $config = new CardConfig();
        $config->upsave(['uniacid' => $this->_uniacid], $params);
        return $this->success([]);
    }

    public function sms_conf_info()
    {
        $config = new CardConfig();
        $info = $config->getinfo(['uniacid' => $this->_uniacid]);
        return $this->success($info);
    }





    //统计htmlspecialchars_encode
    public function order_statistics()
    {
        $param = $this->_param;
        //销售金额
        $company = new CardCompany();
        $order = new CardShopOrder();
        $where =[
            ['pay_status','=',1],
            ['order_status','=',3],
            ['uniacid','=',$this->_uniacid]
        ];
        if (!empty($param['company_id'])) {
            $company_list = array_unique($company->getCompanyUser_l($param['company_id']));
            $where = [
                ['a.company_id','in',$company_list],$where
            ];
        }
        $arr['day_sales_amount'] = $order->toDay($where);
        //客户数量
        $card_count = new CardCount();
        $wheres =[
            ['b.is_staff','=',1],
            ['sign','=','praise'],
            ['type','=',2],
            ['a.uniacid','=',$this->_uniacid]
        ];
        if (!empty($param['company_id'])) {
            $wheres = [
                ['b.company_id','in',$company_list],$wheres
            ];
        }
        $today = $card_count->getCountUser($wheres,'today');
        $yesterday = $card_count->getCountUser($wheres,'yesterday');
        if ($yesterday == 0) {
            $proportion = 0;
        } else {
            $proportion = $today / $yesterday * 100;
        }
        $up = $today>=$yesterday?1:0;
        $arr['today_user'] = ['user_today' => $today,'up'=>$up ,'user_proportion' => round($proportion, 2)];
        //员工数量
        $user_info = new UserInfo();
        if (!empty($data['company_id'])) {
            $where1['company_id'] = $data['company_id'];
        }
        $where1['b.is_staff'] = 1;
        $where1['b.uniacid'] = $this->_uniacid;
        $where1['a.uniacid'] = $this->_uniacid;
        //设置为名片的人数
        $where1['b.status'] = 1;
        $where1['a.is_staff'] = 1;
        $where1['b.deleted'] = 0;
        $arr['surplus_staff_user'] = $user_info->userStaff($where1);
        //部门的统计
        $where3['a.uniacid'] = $this->_uniacid;
        $where3['a.status'] = 1;

        if (empty($param['company_id'])) {
            $arr['job_user'] = $company->getCompanyUserNumber($where3);
        } else {
            $arr['job_user'] = $company->getJobUser($param['company_id'], $this->_uniacid);
        }
        //未设置为名片的人数
        // $where1['status'] = -1;CardauthConfig

        //By.jingshuixian
        //$card_number = LONGBING_AUTH_CARD;
        $permissionCard = new \app\card\info\PermissionCard($this->_uniacid) ;
        $card_number = $permissionCard->getAuthNumber() ;

        $bb = true;
        if($card_number==0){
            $config = new CardauthConfig();
            $aa = true;
            if($config->is_table()){
                $card = $config->getinfo(['modular_id'=>$this->_uniacid]);
                if($card){
                    if($card['number']>0){
                        $card_number = $card['number'];
                    }else{
                        $bb = false;
                        $card_number = '无限制';
                    }
                }else{
                    $aa = false;
                }
            }else{
                $aa = false;
            }
            if($aa ==false){
                $card_auth = new Cardauth2DefaultModel();
                if($card_auth->is_table()){
                    $card = $card_auth->getinfo();
                    if(empty($card)){
                        $card_number  = 5;
                    }else{
                        if($card['card_number']>0){
                            $card_number = $card['card_number'];
                        }else{
                            $bb = false;
                            $card_number = '无限制';
                        }
                    }
                }else{
                    $bb = false;
                    $card_number = '请安装代理端';
                }
            }
        }
        if($bb == false){
            $arr['staff_user'] = $card_number;
        }else{
            $card_number = $card_number-$arr['surplus_staff_user'];
            $arr['staff_user'] = is_numeric($card_number)&&$card_number<0?0:$card_number;//$user_info->userStaff($where1);
        }
        //销量排行
        $admin_goods = new AdminShopOrderGoods();
        $where2 =[
            ['a.status','=',1],
            ['a.uniacid','=',$this->_uniacid]
        ];
        if (!empty($param['company_id'])) {
            $where2 = [
                ['b.company_id','in',$company_list],$where2
            ];
        }
        $arr['sales_count'] = $admin_goods->getGoosNember($where2);
        //销售业绩
        $time = '';
        if (!empty($param['time'])) {
            if ($param['time'] == 7) {
                $time = '-7 day';
            } elseif ($param['time'] == 15) {
                $time = '-15 day';
            } elseif ($param['time'] == 30) {
                $time = '-30 day';
            }
        }
        if (empty($param['company_id'])) {
            $where4['a.uniacid'] = $this->_uniacid;
            $where4['a.pid'] = 0;
            $arr['sales_sum'] = $company->getOrderSum($where4,$time);
        } else {
            $company_list2 = array_unique($company->getCompanyUser_top($param['company_id']));
            $where3 = [
                ['a.id', 'in', $company_list2],
                ['a.uniacid', '=', $this->_uniacid]
            ];
            $arr['sales_sum'] = $company->getOrderSum($where3, $time);
        }

        return $this->success($arr);
    }
    public function company_list_or(){
        $card_company = new CardCompany();
        $where = [
            ['status', '=', 1],
            ['pid', '=', 0],
            ['uniacid', '=', $this->_uniacid]
        ];
        $Company = $card_company->getlist($where);
        return $this->success($Company);
    }
}
